package com.cold.msmservice.controller;

import com.cold.commonutils.R;
import com.cold.msmservice.service.MsmService;
import com.cold.msmservice.utils.RandomUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author cold_and_cold
 * @create 2021-02-04 11:10
 */
@RestController
@RequestMapping("/msmservice/message")
public class MsmController {
    @Autowired
    private MsmService msmService;

    @Autowired
    private RedisTemplate<String ,String> template;

    @GetMapping("send/{phone}")
    public R sendMessage(@PathVariable String phone){
        String code = template.opsForValue().get(phone);
        if(!StringUtils.isEmpty(code)){
            return R.ok().data("code",code);
        }
        code = RandomUtil.getFourBitRandom();
        Map<String,Object> param = new HashMap<>();
        param.put("code", code);
        boolean isSend = msmService.send(phone, "SMS_211260622", param);
        if(isSend) {
            template.opsForValue().set(phone, code,5, TimeUnit.MINUTES);
            return R.ok();
        } else {
            return R.error().message("发送短信失败");
        }
    }
}
